
package reppconn;

import java.util.Stack;

public class XPath {
    
    private Stack<String> pileNode;
    private Stack<Integer> pileId;
    private String lastClosedNode;
    private int lastClosedId;
    private boolean lastActIsGoBack;
    
    public XPath() {
        this.lastActIsGoBack = false;
        this.pileNode = new Stack<String>();
        this.pileId = new Stack<Integer>();
    }
    
        
    public void reset() {
        this.pileNode.clear();
        this.pileId.clear();
        this.lastActIsGoBack = false;
        this.lastClosedNode = null;
    }
    
    public void goIn(String name) {
        if (lastActIsGoBack && lastClosedNode.equals(name)) {
            this.goInWithId(name, lastClosedId+1);
        } else {
            this.goInWithId(name, 1);
        }
        lastActIsGoBack = false;
    }
    
    private void goInWithId(String name, int id) {
        this.pileNode.push(name);
        this.pileId.push(id);
    }
    
    public void goBack() {
        this.lastActIsGoBack = true;
        this.lastClosedNode = pileNode.pop();
        this.lastClosedId = pileId.pop();
    }
    
    public String getXPath() {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i<pileNode.size(); i++) {
            res.append('/').append(pileNode.get(i)).append('[').append(pileId.get(i)).append(']');
        }
        return res.toString();
    }
    
    @Override
    public String toString() {
        return this.getXPath();
    }
    
}
